package com.woniuxy.cloud.depositassembly.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 属性转换工具
 *
 * @author 周川雄
 * @date 2022/1/3 20:38
 */
public class WoniuBeanUtils {
    /**
     * 模拟转换类型
     *
     * @param source
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T copyObject(Object source, Class<T> type) {
        T t = null;
        try {
            t = type.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        BeanUtils.copyProperties(source, t);
        return t;
    }


    //    SuppressWarnings压制警告,即去除警告
    //    rawtypes是说传参时也要传递带泛型的参数

    /**
     * 集合 模拟转换类型
     *
     * @param source
     * @param type   集合
     * @param <T>    泛型.class
     * @return
     */
    public static <T> List<T> copyList(@SuppressWarnings("rawtTpyes") Collection source, Class<T> type) {
        List<T> lists = new ArrayList<T>();
        for (Object obj : source) {
            T t = null;
            try {
                t = type.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            BeanUtils.copyProperties(obj, t);
            lists.add(t);
        }
        return lists;
    }
}
